/*
 * @lc app=leetcode.cn id=59 lang=javascript
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
/**
 * @param {number} n
 * @return {number[][]}
 */
var generateMatrix = function (n) {
  const result = new Array(n).fill(0).map((_) => new Array(n).fill(-1));
  let current = 1;
  let top = 0;
  let bottom = n - 1;
  let left = 0;
  let right = n - 1;

  while (true) {
    for (let i = left; i <= right; i++) {
      result[left][i] = current++;
    }
    if (++top > bottom) break;
    for (let i = top; i <= bottom; i++) {
      result[i][right] = current++;
    }
    if (left > --right) break;
    for (let i = right; i >= left; i--) {
      result[bottom][i] = current++;
    }
    if (top > --bottom) break;
    for (let i = bottom; i >= top; i--) {
      result[i][left] = current++;
    }
    if (++left > right) break;
  }

  return result;
};
// @lc code=end
